import java.security.Key;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-05-18
 * Time: 22:31
 */
public class Solution {
    public int len;
    public int[] prefix;

    public Solution(int[] w) {
        this.len = w.length;
        this.prefix = new int[len];
        prefix[0] = w[0];
        for (int i = 1; i < len; i++) {
            prefix[i] = prefix[i - 1] + w[i];
        }
    }

    public int pickIndex() {
        Random random = new Random();
        int value = random.nextInt(prefix[len - 1]) + 1;
        int left = 0;
        int right = len - 1;
        while (left < right){
            // 防止数字溢出
            int mid = (right - left) / 2 + left;
            // 不用判断的那么复杂
            if (prefix[mid] < value){
                left = mid + 1;
            }else{
                right = mid;
            }
        }
        return left;
    }
}